<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Exceptions in Java EE 5</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, Java, web applications, Java Servlets, Exceptions">
<meta name="description" content="This part of the Java EE 5 tutorials covers exceptions.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Contents">Contents</a>



<h1>Exceptions</h1>

<p>
In this part of the JEE tutorials we will work with Exceptions.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
An <b>exception</b> is a condition, often an error, that causes a program to 
call a different routine. Exceptions should be divided in some logical groups. 
For example, we can divide exceptions into application exceptions and system 
exceptions. System exceptions react to low level system errors. Like memory 
shortage, lost connection etc. Application exceptions are higher level errors. 
They are usually less serious. They occur when some rules in application logic are broken.
For example, when a user enters invalid data, an application exception is called.
</p>

<p>
In our next example, we will work with both kinds of exceptions. We will react to 
three kind of system exceptions and one kind of application exception. We will 
have system errors and application warnings. To inform user about exceptions, we will 
create message windows. This will be created using css and JavaScript. The example is quite 
complicated. Works on Firefox and Opera.
</p>

<div class="codehead">style.css</div>
<pre class="code">
* { font-size: 12px; font-family: Verdana }

form { margin-top: 5%; }

input, textarea { border: 1px solid #ccc }

.message { 
  position: absolute;
  display: none;
  background: #577580;
  width: 235px;
  height: 150px;
  cursor: move;
  padding: 5px;
  color: white;
}

.header {
  font-weight: bolder;
  margin-bottom: 7px;
}

a#close { 
  position: absolute;
  display: block; 
  border: 1px solid #ccc; 
  padding: 2px;
  width: 60px;
  bottom: 20px;
  left: 88px; 
  text-decoration: none;
  font-weight: bolder;
  color: white;
}
</pre>

<p>
This is a stylesheet applied to our example. The <code>.message</code> 
class creates a message window for us. It is initially not visible. 
The <code>.header</code> class creates header of the message window. 
The <code>close</code> selector defines style for an anchor, that will 
serve as our close button.
</p>

<div class="codehead">util.js</div>
<pre class="code">
var savedTarget = null;
var orgCursor = null;  
var dragOK = false;     
var dragXoffset = 0;   
var dragYoffset = 0;  

function showError() {
    if (msg.style.display == 'block') {
        msg.style.display = 'none';
        msg.innerHTML = ''; 
    } else {
        msg.style.display = 'block';
        msg.innerHTML = '&lt;b&gt;Error&lt;/b&gt;&lt;p&gt;';
        var string = error + '&lt;/p&gt;&lt;center&gt;';
        string += '&lt;a id="close" href="javascript:showError()"&gt;';
        string += 'close&lt;/a&gt;&lt;/center&gt;';
        msg.innerHTML += string;
    }
}

function showWarning() {
    if (msg.style.display == 'block') {
        msg.style.display = 'none';
        msg.innerHTML = ''; 
    } else {
        msg.style.display = 'block';
        msg.innerHTML = '&lt;b&gt;Warning&lt;/b&gt;&lt;p&gt;';
        var string = warning + '&lt;/p&gt;&lt;center&gt;';
        string += '&lt;a id="close" href="javascript:showWarning()"&gt;';
        string += 'close&lt;/a&gt;&lt;/center&gt;';
        msg.innerHTML += string;
   }
}

function moveHandler(e){
    if (e == null) { e = window.event } 
    if (e.button &lt;= 1 &amp;&amp; dragOK){
        savedTarget.style.left = e.clientX - dragXoffset + 'px';
        savedTarget.style.top = e.clientY - dragYoffset + 'px';
        return false;
    }
}

function cleanup(e) {
    document.onmousemove = null;
    document.onmouseup = null;
    savedTarget.style.cursor = orgCursor;
    dragOK = false;
}

function dragHandler(e){
    var htype='-moz-grabbing';
    if (e == null) { e = window.event; htype = 'move';} 
    var target = e.target != null ? e.target : e.srcElement;
    orgCursor = target.style.cursor;

    if (target.className == "message") {
        savedTarget = target;
        target.style.cursor = htype;
        dragOK = true;
        dragXoffset = e.clientX - parseInt(msg.style.left);
        dragYoffset = e.clientY - parseInt(msg.style.top);
        document.onmousemove = moveHandler;
        document.onmouseup = cleanup;
        return false;
    }
}

document.onmousedown = dragHandler;
</pre>

<p>
The util.js file will have most of the javascript code. 
The <code>showWarning()</code>  function displays the 
application warning message window, the <code>showError()</code> displays 
the system error message window. The <code>moveHandler()</code>, 
<code>cleanup()</code> and <code>dragHandler()</code> 
fuctions enable to move the window with the mouse pointer. The javascript 
code is adapted from <a href="http://www.hunlock.com">hunlock.com</a>.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;


&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
&lt;title&gt;Exceptions&lt;/title&gt;

&lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
&lt;script src="util.js" type="text/javascript" &gt;&lt;/script&gt;

&lt;script  type="text/javascript"&gt;

&lt;%!
  String error;
  String warning;
  String okm;
%&gt;

&lt;%
  error = (String) request.getAttribute("ErrorMessage");
  warning = (String) request.getAttribute("Warning");
  okm = (String) request.getAttribute("OkMessage");
%&gt;

  var error = "&lt;%=error%&gt;";
  var warning = "&lt;%=warning%&gt;";
  var okm = "&lt;%=okm%&gt;";
&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
  &lt;h2&gt;Exceptions&lt;/h2&gt;

  &lt;center&gt;
    &lt;form action="ProcessServlet" &gt;   
      &lt;table&gt;
        &lt;tr&gt;
          &lt;td&gt;From&lt;/td&gt;
          &lt;td&gt;&lt;input type="text" name="from"&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;To&lt;/td&gt;
          &lt;td&gt;&lt;input type="text" name="to"&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;   
          &lt;td&gt;Subject&lt;/td&gt;
          &lt;td&gt;&lt;input type="text" name="subject"&gt;&lt;/td&gt;
        &lt;/tr&gt;    
        &lt;tr&gt;
          &lt;td&gt;Message&lt;/td&gt;
          &lt;td&gt;&lt;textarea cols="25" rows="8" name="message"&gt;&lt;/textarea&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
     &lt;br&gt;
     &lt;input type="submit" value="submit"&gt;
   &lt;/form&gt;
  &lt;/center&gt;

&lt;div id="messageID" class="message"&gt;&lt;/div&gt;

&lt;script  type="text/javascript"&gt;

  msg = document.getElementById('messageID');
  msg.style.top = (window.innerHeight-235) / 2;
  msg.style.left = (window.innerWidth-150) / 2;

&lt;/script&gt;

&lt;%
   if (error != null) {
%&gt;

&lt;script&gt;
   showError();
&lt;/script&gt;

&lt;% } else if (warning != null) { %&gt;
    &lt;script  type="text/javascript"&gt;
         showWarning();
    &lt;/script&gt;

&lt;% } else if (okm != null) {
          out.print(okm);
   } %&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
The index.jsp file creates a html form. It is also a place, where 
message windows will pop up.
</p>

<pre class="explanation">
var error = "&lt;%=error%&gt;";
var warning = "&lt;%=warning%&gt;";
var okm = "&lt;%=okm%&gt;";
</pre>

<p>
Here we can see, how data from java code is passed to javascript. These 
JavaScript variables will determine, which message window will appear on the screen.
</p>

<pre class="explanation">
&lt;div id="messageID" class="message"&gt;&lt;/div&gt;
</pre>

<p>
The message window is a simple div tag. It is initially not visible. If an 
exception occurs, the div is made visible by the javascript code. The visibility 
of the tag is changed from none to block.
</p>

<pre class="explanation">
msg = document.getElementById('messageID');
msg.style.top = (window.innerHeight-235) / 2;
msg.style.left = (window.innerWidth-150) / 2;
</pre>

<p>
This javascript code positions the window into the middle of the screen.
</p>

<pre class="explanation">
&lt;%
   if (error != null) {
%&gt;

&lt;script&gt;
   showError();
&lt;/script&gt;

&lt;% } else if (warning != null) { %&gt;
    &lt;script  type="text/javascript"&gt;
         showWarning();
    &lt;/script&gt;

&lt;% } else if (okm != null) {
          out.print(okm);
   } %&gt;
</pre>

<p>
This embedded java code decides, which message window to display. 
If no exception occurs, we simply output All OK message.
</p>

<img src="/img/java/jee/messagewindow.png" alt="Message Window">
<div class="figure">Figure: Message Window</div>


<div class="codehead">Process.java</div>
<pre class="code">
package com.zetcode;

import java.io.*;
import java.net.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import com.mysql.jdbc.CommunicationsException;

public class Process extends HttpServlet {

  protected void processRequest(HttpServletRequest request, 
                                HttpServletResponse response)
          throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

    Connection con;
    String url = "jdbc:mysql://localhost:3306/";

    try {

        this.testForm(request);
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url, "root", "");
        con.close();

    } catch (CommunicationsException ex) {
        request.setAttribute("ErrorMessage", 
                             "Cannot connect to database");

        RequestDispatcher dispatcher = 
                          request.getRequestDispatcher("/index.jsp");

        dispatcher.forward(request, response);

    } catch (SQLException ex) {
        request.setAttribute("ErrorMessage", ex.getMessage());

        RequestDispatcher dispatcher = 
                          request.getRequestDispatcher("/index.jsp");

        dispatcher.forward(request, response);

    } catch (ClassNotFoundException ex) {
        request.setAttribute("ErrorMessage", "MySQL driver not found");

        RequestDispatcher dispatcher = 
                          request.getRequestDispatcher("/index.jsp");

        dispatcher.forward(request, response);

    } catch (UserException ex) {
        request.setAttribute("Warning", ex.getMessage());

        RequestDispatcher dispatcher = 
                          request.getRequestDispatcher("/index.jsp");

        dispatcher.forward(request, response);
    }

    request.setAttribute("OkMessage", "All OK");
    RequestDispatcher dispatcher = 
                      request.getRequestDispatcher("/index.jsp");

    dispatcher.forward(request, response);
  }

  public void testForm(HttpServletRequest request) throws UserException {

    String from = (String) request.getParameter("from");
    String to = (String) request.getParameter("to");
    String subject = (String) request.getParameter("subject");
    String message = (String) request.getParameter("message");

    if (from.isEmpty()  || to.isEmpty() || 
             subject.isEmpty() || message.isEmpty() ) {
        throw new UserException("Form not correctly filled");
    }

  }

  protected void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
          throws ServletException, IOException {
      processRequest(request, response);
  }

  protected void doPost(HttpServletRequest request, 
                        HttpServletResponse response)
          throws ServletException, IOException {
      processRequest(request, response);
  }
}
</pre>

<p>
This is the servlet, where the exceptions arise. It does nothing in particular, 
only enables us the test various error conditions.  The servlet will react to 
four different exceptions: <code>CommunicationsException</code>, 
<code>SQLException</code>, <code>ClassNotFoundException</code> 
and <code>UserException</code>. We can test the CommunicationsException 
by shutting down the MySQL database. The SQLException will arise, when we e.g.
provide invalid password to the database user. If we do not include MySQL driver 
library , we will have the ClassNotFoundException. Finally, the UserExeption will 
occur, when at least one of the form parameters is empty.
</p>

<pre class="code">
sudo /etc/init.d/mysql stop
</pre>

<p>
Here we stop the MySQL database server.
</p>

<pre class="explanation">
} catch (CommunicationsException ex) {
    request.setAttribute("ErrorMessage", 
                         "Cannot connect to database");

     RequestDispatcher dispatcher = 
                      request.getRequestDispatcher("/index.jsp");

    dispatcher.forward(request, response);
} 
</pre>

<p>
This exception will react to the system error, caused by the lost connection. 
The code sets an attribute to the 
request and forwards back to the index.jsp page.
</p>


<pre class="explanation">
public void testForm(HttpServletRequest request) throws UserException {

  String from = (String) request.getParameter("from");
  String to = (String) request.getParameter("to");
  String subject = (String) request.getParameter("subject");
  String message = (String) request.getParameter("message");

  if (from.isEmpty()  || to.isEmpty() || 
           subject.isEmpty() || message.isEmpty() ) {
      throw new UserException("Form not correctly filled");
  }
}
</pre>

<p>
The <code>testForm()</code> method will test if all parameters 
are set. If not, we throw an UserExeption.
</p>

<div class="codehead">UserException.java</div>
<pre class="code">
package com.zetcode;


public class UserException extends Exception {

  public UserException(String msg) {
      super(msg);
  }

  public String getMessage() {
      return super.getMessage();
  }
}
</pre>

<p>
The UserException is an application exception. This exception will cause 
the warning message windows.
</p>

<p>
In this chapter we have briefly mentioned exceptions.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 30, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

